/**
 * 
 */
package com.wolfpire.system.dao.impl;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.collections.CollectionUtils;
import org.hibernate.Criteria;
import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Repository;

import com.wolfpire.subject.dao.ProfessionSubjectRelationDao;
import com.wolfpire.subject.dao.UserGroupSubjectRelationDao;
import com.wolfpire.system.common.base.dao.impl.BaseHibernateDao;
import com.wolfpire.system.dao.OrgUserRelationDao;
import com.wolfpire.system.dao.UserGroupUserRelationDao;
import com.wolfpire.system.model.OrgUserRelation;
import com.wolfpire.system.model.ProfessionSubjectRelation;
import com.wolfpire.system.model.RoleAuthorityRelation;
import com.wolfpire.system.model.Section;
import com.wolfpire.system.model.UserGroupSubjectRelation;
import com.wolfpire.system.model.UserGroupUserRelation;

/**
 * 用户组课程关联关系
 * @author lihd
 *
 */

@Repository("userGroupUserRelationDao")
public class UserGroupUserRelationDaoImpl extends BaseHibernateDao<UserGroupUserRelation, Long> implements UserGroupUserRelationDao {

	public void relate(Long usergroupId, Long userId) {
		// TODO Auto-generated method stub
		this.deleteByUserGroupId(usergroupId);
		if (null != userId) {
			UserGroupUserRelation ugu = new UserGroupUserRelation(usergroupId,userId);
			this.saveOrUpdate(ugu);
		}
		
	}
	
	private void deleteByUserGroupId(Long usergroupId) {
		String executeSql = "DELETE FROM t_usergroup_user WHERE usergroup_id = ?";
		this.executeSql(executeSql, usergroupId);
	}

	public void relate(Long usergroupId, List<Long> userIds) {
		//先删除后绑定
		this.deleteByUserGroupId(usergroupId);
		if (CollectionUtils.isNotEmpty(userIds)) {
			Session session = this.getSession();
			int size = userIds.size();
			for (int i = 0; i < size; i++) {
				UserGroupUserRelation ugu = new UserGroupUserRelation(usergroupId,userIds.get(i));
				session.save(ugu);
				if ((i + 1) % 50 == 0) {
					session.flush();
					session.clear();
				}
			}
		}
		
	}

	public UserGroupUserRelation getUGSRelation(Long usergroupId) {
		Criteria c = createCriteria(Restrictions.eq("usergroupId", usergroupId));
		Object obj = c.uniqueResult();
		if (null != obj) {
			return (UserGroupUserRelation) obj;
		}
		return null;
	}
	
}
